package com.example.wuyeguanli.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.wuyeguanli.R;
import com.example.wuyeguanli.entiy.Owner;
import com.example.wuyeguanli.entiy.Response;
import com.example.wuyeguanli.tools.ApiClient;
import com.example.wuyeguanli.tools.DataValidator;

public class RegisterLoginActivity extends AppCompatActivity {
    private final String TAG = "ApiClient";
    private EditText phone;
    private EditText password;
    private Button login;
    private Button register;
    private ProgressBar loading_progress;
    private final ApiClient apiClient = new ApiClient();

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registerlogin);
        if(getSupportActionBar() != null) getSupportActionBar().hide();

        phone = findViewById(R.id.phone);
        password = findViewById(R.id.password);
        login = findViewById(R.id.login);
        register = findViewById(R.id.register);
        loading_progress = findViewById(R.id.loading_progress);

        login.setOnClickListener(v -> handleLogin());
        register.setOnClickListener(v -> {
            Intent intent = new Intent(RegisterLoginActivity.this, RegisterActivity.class);
            startActivity(intent);
        });
    }

    private void handleLogin() {
        setLoadingState(true);
        String phoneStr = phone.getText().toString();
        String passwordStr = password.getText().toString();

        if (!DataValidator.isValidPhoneNumber(phoneStr) || !DataValidator.isValidPassword(passwordStr)) {
            Toast.makeText(this, "手机号或密码格式不正确", Toast.LENGTH_SHORT).show();
            setLoadingState(false);
            return;
        }

        // 重构: 登录流程简化，直接调用login接口
        apiClient.login(phoneStr, passwordStr, new ApiClient.OnCompleteListener<Response<Object>>() {
            @Override
            public void onSuccess(Response<Object> data) {
                if (data.getState().equals("success")) {
                    // 登录成功后，再获取用户信息以保存用户名
                    fetchUserDetailsAndProceed(phoneStr);
                } else {
                    Toast.makeText(RegisterLoginActivity.this, data.getError(), Toast.LENGTH_SHORT).show();
                    setLoadingState(false);
                }
            }

            @Override
            public void OnError(Throwable error) {
                Log.e(TAG, "Login OnError: ", error);
                Toast.makeText(RegisterLoginActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show();
                setLoadingState(false);
            }
        });
    }

    private void fetchUserDetailsAndProceed(String phone) {
        apiClient.findUser(phone, new ApiClient.OnCompleteListener<Response<Owner>>() {
            @Override
            public void onSuccess(Response<Owner> data) {
                setLoadingState(false);
                if (data.getState().equals("success") && data.getData() != null) {
                    Owner owner = data.getData();
                    SharedPreferences sharedPreferences = getSharedPreferences("user", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("username", owner.getUsername());
                    editor.putBoolean("login", true);
                    editor.apply();

                    Intent intent = new Intent(RegisterLoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    // 理论上登录成功后，这里不应该失败，但作为防御性编程处理
                    Toast.makeText(RegisterLoginActivity.this, "登录成功，但获取用户信息失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void OnError(Throwable error) {
                setLoadingState(false);
                Log.e(TAG, "FindUser OnError: ", error);
                Toast.makeText(RegisterLoginActivity.this, "网络错误，获取用户信息失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setLoadingState(boolean isLoading) {
        loading_progress.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        phone.setEnabled(!isLoading);
        password.setEnabled(!isLoading);
        login.setEnabled(!isLoading);
        register.setEnabled(!isLoading);
    }
}